﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace _18_限流器
{
    public class XianLiuFilter : IAsyncActionFilter
    {
        private readonly IMemoryCache memoryCache;
        public  XianLiuFilter(IMemoryCache memoryCache) {
            this.memoryCache = memoryCache;
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string ip = context.HttpContext.Connection.RemoteIpAddress.ToString(); //获取IP
            string catchKey = $"LastVisitTick_{ip}";
            long? lastTick = memoryCache.Get<long?>(catchKey);
            if (lastTick == null || Environment.TickCount64 - lastTick > 1000)
            {
                memoryCache.Set(catchKey, Environment.TickCount64, TimeSpan.FromSeconds(10));  // 10内存失效，避免长期不访问用户，占据缓存内存
                await next();
            }
            else {
                context.Result = new ObjectResult("访问太频繁了"){ StatusCode = 429 };
                Console.WriteLine("限流......");
                // return Task.CompletedTask;
            }
        }
    }
}
